﻿var keyValue = request('keyValue');

var companyId = request('companyId');
var departmentId = request('departmentId');

var personKeyword = "";
var personSpellChar = "";

var cityKeyword = "";
var citySpellChar = "";

var index = request("index");
var result = {};

var removeSelectPerson;
var addSelectPerson;

var removeSelectCity;
var addSelectCity;
var openSelectCity;
var toggleVehicle;
var switchVehicle;
var changeTime;

var acceptClick;
var bootstrap = function ($, learun) {
    "use strict";

    var currentThougthline;
    var currentThougthlineIndex;
    var currentCityIndex;

    //判断选择出行人员是否重复
    function isRepeatPerson(id) {
        var res = false;
        for (var i = 0, l = result.persons.length; i < l; i++) {
            if (result.persons[i].id == id) {
                res = true;
                break;
            }
        }
        return res;
    }

    //添加出行人员
    addSelectPerson = function (id) {
        var userName = $(id).html();
        var userId = $(id).attr("data-id");
        if(!isRepeatPerson(userId)) {
            var user = {id:userId, realName:userName}
            result.persons.push(user);

            var $html =  '<div class="oppbox" style="margin-right:10px;" data-id="'+userId+'"> ';
                $html+=  '   <span class="oppbox-text black" style="color:#000;">'+userName+'</span>';
                $html+=  '   <div class="oppbox oppbox-item-del" onclick="removeSelectPerson(this)">&nbsp;</div>';
                $html+=  '</div>';
            $("#pnlTravelPerson").append($html);
        }
    }

    //删除出行人员
    removeSelectPerson = function (id) {
        var userId = $(id).parent().attr("data-id");
        for (var i = 0, l = result.persons.length; i < l; i++) {
            if (result.persons[i].id == userId) {
                result.persons.splice(i, 1);
                break;
            }
        }
        $(id).parent().remove();
    }

    //检索出行人员
    function searchPerson(keyword, simpleSpelling) {
        var paramStr =  "";
        if(!!companyId) {
            paramStr += "&companyId=" + companyId;
        }
        if(!!departmentId) {
            paramStr += "&departmentId=" + departmentId;
        }
        if(!!keyword) {
            paramStr += "&keyword=" + keyword;
        }
        if(!!simpleSpelling) {
            paramStr += "&simpleSpelling=" + simpleSpelling;
        }
        learun.httpAsyncGet2(config.base_server() + 'users/list', paramStr, function (res) {
            learun.loading(false);

            if (res.resp_code == 200) {
                $("#pnlTravelSelectPersonResult").empty();
                var $html = "";
                for (var i = 0, l = res.data.length; i < l; i++) {
                    $html += '<div class="oppbox oppbox-gray" style="margin-right:10px;"><a href="javascript:void(0);" onclick="addSelectPerson(this)" data-id="'+res.data[i].id+'" class="oppbox-text">'+res.data[i].realName+'</a></div>';
                }
                if($html=='') {
                    $html = '<span class="nk-receipt-label b i" n="查找结果" style="width: auto; color: rgb(238, 17, 17); display: inline-block;">查找不到对应的人员，请重新查找...</span>';
                }
                $("#pnlTravelSelectPersonResult").append($html);
            }
        });
    }

    //显示城市选择框
    openSelectCity = function (id) {
        var _index = $(id).attr("data-index");
        currentCityIndex = _index;
        learun.layerForm({
            id: 'form_selectCity',
            title: '选择城市',
            url: config.webportal_server + 'pages/system/standard/hotel/select.html?access_token=' + config.getToken().access_token,
            height: 670,
            width: 800,
            callBack: function (id) {
                return top[id].acceptClick(addSelectCity);
            }
        });
    }

    //添加城市
    addSelectCity = function (id, cityObj) {
        var cityId,cityName;
        if(!!id) {
           cityId = $(id).attr("data-id");
           cityName = $(id).html();
        } else {
           cityId = cityObj.cityId;
           cityName = cityObj.cityName;
        }
        var currentDate = new Date();
        var year = currentDate.getFullYear();
        var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
        var day = ("0" + currentDate.getDate()).slice(-2);
        var today = year + "-" + month + "-" + day;

        var city = {id:cityId, cityName:cityName,vehicle:"飞机", startDate:today,endDate:today}

        if(!!id) {
            if(result.travels.length < 2) {
                result.travels.push(city);
            } else {
                result.travels.splice(result.travels.length-1, 0, city);
            }
        } else {
            result.travels.splice(currentCityIndex, 0, city);
        }
        redrawRoute();
    }

    //删除城市
    removeSelectCity = function (id) {
        var cityId = $(id).attr("data-id");
        for (var i = 0, l = result.travels.length; i < l; i++) {
            if (result.travels[i].id == cityId) {
                result.travels.splice(i, 1);
                break;
            }
        }
        redrawRoute();
    }

    //检索城市
    function searchCity(keyword, simpleSpelling) {
        var paramStr =  "&layer=2";
        if(!!keyword) {
            paramStr += "&keyword=" + keyword;
        }
        if(!!simpleSpelling) {
            paramStr += "&simpleSpelling=" + simpleSpelling;
        }
        learun.httpAsyncGet2(config.base_server() + 'areas', paramStr, function (res) {
            learun.loading(false);

            if (res.resp_code == 200) {
                $("#pnlTravelSelectCityResult").empty();
                var $html = "";
                for (var i = 0, l = res.data.length; i < l; i++) {
                    $html += '<div class="oppbox oppbox-gray" style="margin-right:10px;"><a href="javascript:void(0);" onclick="addSelectCity(this)" data-id="'+res.data[i].id+'" class="oppbox-text">'+res.data[i].areaName+'</a></div>';
                }
                if($html=='') {
                    $html = '<span class="nk-receipt-label b i" n="查找结果" style="width: auto; color: rgb(238, 17, 17); display: inline-block;">查找不到对应的城市，请重新查找...</span>';
                }
                $("#pnlTravelSelectCityResult").append($html);
            }
        });
    }

    //绘制行程图
    function redrawRoute() {
       $("#pnlTravelCity").empty();
       var $html = "";
       for (var i = 0, l = result.travels.length; i < l; i++) {
           $html+=  '<div class="oppbox oppbox-item-add" data-index="'+i+'" data-id="'+result.travels[i].id+'" onclick="openSelectCity(this)">&nbsp;<br>&nbsp;</div>';
           $html+=  '<div class="oppbox oppbox-border oppbox-city">';
           $html+=  '   <p><a class="oppbox-text b city-name">'+result.travels[i].cityName+'</a></p>';
           if(i > 0) {//第一个起点
                $html+=  '   <p>到达：<input type="text" value='+result.travels[i].endDate+' onclick="WdatePicker({dateFmt:\'yyyy-MM-dd\',qsEnabled:false,isShowClear:false,isShowToday:false,onpicked:function(){$(id).trigger(\'change\');}});" onchange="changeTime(this,'+Number(i+1)+')" class="oppbox-text time-arrive" style="border: none;background-color: transparent;width: 82px;color: darkgray;"/></p>';
           }
           if(i == 0 || i+1 < l) {//第二个终点
                $html+=  '   <p>出发：<input type="text" value='+result.travels[i].startDate+' onclick="WdatePicker({dateFmt:\'yyyy-MM-dd\',qsEnabled:false,isShowClear:false,isShowToday:false,onpicked:function(){$(id).trigger(\'change\');}});" onchange="changeTime(this,'+Number(i+1)+')" class="oppbox-text time-go" style="border: none;background-color: transparent;width: 82px;color: darkgray;"/></p>';
           }
           $html+=  '</div>';
           $html+=  '<div class="oppbox oppbox-item-del" data-id="'+result.travels[i].id+'" onclick="removeSelectCity(this)">&nbsp;<br>&nbsp;</div>';
           if(i+1 < l) {//第二个终点
                $html+=  '<div class="oppbox oppbox-thougthline"><a href="javascript:void(0);" onclick="toggleVehicle(this,'+Number(i+1)+')">'+result.travels[i].vehicle+'</a></div>';
           }
       }
       $("#pnlTravelCity").append($html);
    }

    //绘制出行人员
    function redrawPerson() {
       $("#pnlTravelPerson").empty();
       var $html = "";
       for (var i = 0, l = result.persons.length; i < l; i++) {
           $html +=  '<div class="oppbox" style="margin-right:10px;" data-id="'+result.persons[i].id+'"> ';
           $html +=  '   <span class="oppbox-text black" style="color:#000;">'+result.persons[i].realName+'</span>';
           $html +=  '   <div class="oppbox oppbox-item-del" onclick="removeSelectPerson(this)">&nbsp;</div>';
           $html +=  '</div>';
       }
       $("#pnlTravelPerson").append($html);
    }

    //显示交通工具
    toggleVehicle = function(line, index) {
        var obj = $(line).offset();
        currentThougthline = line;
        currentThougthlineIndex = index;
        $("#pnlTravelSelectVehicle").css("top", obj.top+24);
        $("#pnlTravelSelectVehicle").css("left", obj.left);
        if($("#pnlTravelSelectVehicle").is(":visible")) {
            $("#pnlTravelSelectVehicle").hide();
        } else {
            $("#pnlTravelSelectVehicle").show();
        }
    }

    //选择交通工具
    switchVehicle = function(id) {
        var vehicle = $(id).html();
        $(currentThougthline).html(vehicle);
        result.travels[currentThougthlineIndex].vehicle = vehicle;
        $("#pnlTravelSelectVehicle").hide();
    }

    //选择时间
    changeTime = function(id, index) {
        var date = $(id).val();
        if($(id).hasClass("time-arrive")) {
            result.travels[index-1].endDate = date;
        } else  if($(id).hasClass("time-go")) {
            result.travels[index-1].startDate = date;
        }
    }

    var page = {
        init: function () {
            page.bind();
            page.initData();
        },
        /*绑定事件和初始化控件*/
        bind: function () {
            // 查询出行人员列表
            $('#txtTravelSelectPersonFindName').on("keypress", function (e) {
                if (event.keyCode == "13") {
                    var $this = $(this);
                    var keyword = $this.val();
                    searchPerson(keyword, null);
                }
            });
            $('#btnTravelSelectPersonFind').on("click", function (e) {
                var keyword = $("#txtTravelSelectPersonFindName").val();
                searchPerson(keyword, null);
            });
            $('#pnlTravelSelectPersonChar >a').on("click", function (e) {
                var $this = $(this);
                var splling = $this.html();
                searchPerson(null, splling);
            });

            // 查询城市列表
            $('#txtTravelSelectCityFindName').on("keypress", function (e) {
                if (event.keyCode == "13") {
                    var $this = $(this);
                    var keyword = $this.val();
                    searchCity(keyword, null);
                }
            });
            $('#btnTravelSelectCityFind').on("click", function (e) {
                var keyword = $("#txtTravelSelectPersonFindName").val();
                searchCity(keyword, null);
            });
            $('#pnlTravelSelectCityChar >a').on("click", function (e) {
                var $this = $(this);
                var splling = $this.html();
                searchCity(null, splling);
            });
            $('#btnTravelSelectVehicleClose').on("click", function (e) {
                $("#pnlTravelSelectVehicle").hide();
            });
        },
        /*初始化数据*/
        initData: function () {
            if(!!index) {
               result = $(config.getParent(learun).document).find("#wfFormIframe0")[0].contentWindow.routes[index];

               $("input[type='radio'][name='pnlIncludeMeal'][value='"+result.includeMeal+"']").prop("checked","checked");
               $("input[type='radio'][name='pnlIncludeHotel'][value='"+result.includeHotel+"']").prop("checked","checked");
               redrawRoute();
               redrawPerson();
            } else {
                result.persons = [];
                var _travels = [];
                var currentDate = new Date();
                var year = currentDate.getFullYear();
                var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
                var day = ("0" + currentDate.getDate()).slice(-2);
                var today = year + "-" + month + "-" + day;
                var _startCity = {id:"400100",cityName:"广州市",vehicle:"飞机",startDate:today};
                var _endCity = {id:"400100",cityName:"广州市",vehicle:"飞机",endDate:today};
                _travels.push(_startCity);
                _travels.push(_endCity);
                result.travels = _travels;
                redrawRoute();
            }
        }
    };

    // 保存数据
    acceptClick = function (callBack) {
        var pnlIncludeMeal = $("input[type='radio'][name='pnlIncludeMeal']:checked").val();
        var pnlIncludeHotel = $("input[type='radio'][name='pnlIncludeHotel']:checked").val();
        if(!pnlIncludeMeal) {
            learun.alert.warning('请选择地方单位是否包含伙食！');
            $("input[type='radio'][name='pnlIncludeMeal']").focus();
            return false;
        }
        if(!pnlIncludeHotel) {
            learun.alert.warning('请选择地方单位是否包含住宿！');
            $("input[type='radio'][name='pnlIncludeHotel']").focus();
            return false;
        }
        result.includeMeal = pnlIncludeMeal;
        result.includeHotel = pnlIncludeHotel;

        //行程
        var routeList = [];
        var _routeSort = 0;
        $("#pnlTravelCity").find("div").each(function (index) {
            var _$person;
            var $divPanl = $(this).parent().parent();
            var _includeHotel = $divPanl.attr("data-includeHotel");
            var _includeMeal = $divPanl.attr("data-includeMeal");

            var _routeIndex = 0;
            $(this).find("tr").each(function (index) {
                var travel = {};
                var _index = 1;
                if(index==0) {
                    _index = 0;
                    _$person = $(this).children('td').eq(0).children("span");
                }
                var _$startCityDate = $(this).children('td').eq(1-_index).children("span").eq(0);
                var _$startCityName = $(this).children('td').eq(1-_index).children("span").eq(1);
                var _$endCityDate = $(this).children('td').eq(2-_index).children("span").eq(0);
                var _$endCityName = $(this).children('td').eq(2-_index).children("span").eq(1);
                var _$vehicle = $(this).children('td').eq(3-_index).children("span");
                var _$城市间交通费 = $(this).children('td').eq(4-_index).children("input");
                var _$因私天数 = $(this).children('td').eq(5-_index).children("input");
                var _$住宿天数 = $(this).children('td').eq(6-_index).children("input");
                var _$住宿费 = $(this).children('td').eq(7-_index).children("input");
                var _$伙食补助费 = $(this).children('td').eq(8-_index).children("input");
                var _$室内交通费 = $(this).children('td').eq(9-_index).children("input");
                var _$其他费用 = $(this).children('td').eq(10-_index).children("input");
                var _$小计 = $(this).children('td').eq(11-_index);


                travel.includeHotel = _includeHotel;
                travel.includeMeal = _includeMeal;
                travel.personId = _$person.attr("data-id");
                travel.personName = _$person.html();
                travel.startDate = _$startCityDate.html();
                travel.startCity = _$startCityName.html();
                travel.endDate = _$endCityDate.html();
                travel.endCity = _$endCityName.html();
                travel.vehicle = _$vehicle.html();
                travel.amountCityout = $.unformatMoney(_$城市间交通费.val());
                travel.daysPrivate = _$因私天数.val();
                travel.daysHotel = _$住宿天数.val();
                travel.amountHotel = $.unformatMoney(_$住宿费.val());
                travel.amountMeal = $.unformatMoney(_$伙食补助费.val());
                travel.amountCityinner = $.unformatMoney(_$室内交通费.val());
                travel.amountOther = $.unformatMoney(_$其他费用.val());
                travel.amount = $.unformatMoney(_$小计.html());
                travel.billSort = _routeSort;
                travel.billIndex = _routeIndex;

                routeList.push(travel);
                _routeIndex++;
            });
            _routeSort++;
        });

        if (!!callBack) {
            callBack(result, index);
        }
        return true;
    };



    page.init();
}